package com.leyou.item.sevice.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.LyExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.constants.MQConstants;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.dto.SpuDetailDTO;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.Spu;
import com.leyou.item.pojo.SpuDetail;
import com.leyou.item.sevice.BrandService;
import com.leyou.item.sevice.CategoryService;
import com.leyou.item.sevice.GoodsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageResult<SpuDTO> queryPage(Integer page, Integer rows, String key, Boolean saleable) {
        //查询商品列表
        //1 分页查询
        PageHelper.startPage(page,rows);
        //2 条件查询
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        //2.1 key 关键字查询
        if(StringUtils.isNotBlank(key)){
            criteria.andLike("name","%"+key+"%");
        }
        //2.2
        if(saleable!=null){
            criteria.andEqualTo("saleable",saleable);
        }
        //查询
        List<Spu> spus = spuMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(spus)) {
            throw new LyException(LyExceptionEnum.GOODS_NOT_FOUND);
        }

        //转换查询结果，获取查询总记录数
        PageInfo<Spu> pageInfo = new PageInfo<>(spus);

        List<SpuDTO> dtoList = BeanHelper.copyWithCollection(spus, SpuDTO.class);
        //处理品牌名称和分类名称展示
        handlerBrandAndCategory(dtoList);

        return new PageResult<>(pageInfo.getTotal(),dtoList );
    }

    /**
     * 处理品牌名称和分类名称展示
     * @param dtoList
     */
    private void handlerBrandAndCategory(List<SpuDTO> dtoList) {
        for (SpuDTO spuDTO : dtoList) {
            //品牌名称
            spuDTO.setBrandName(brandService.queryById(spuDTO.getBrandId()).getName());
            //规格名称处理
            List<CategoryDTO> categoryDTOList = categoryService.queryByCategoryIds(spuDTO.getCategoryIds());
            /*String categroyName = "";
            for (CategoryDTO categoryDTO : categoryDTOList) {
                categroyName +=categoryDTO.getName()+"/";
            }
            spuDTO.setCategoryName(categroyName);*/
            String categoryName = categoryDTOList.stream().map(CategoryDTO::getName).collect(Collectors.joining("/"));
            spuDTO.setCategoryName(categoryName);
        }

    }

    @Override
    public void saveGoods(SpuDTO spuDTO) {
        //保存spu
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        spu.setId(null);
        spu.setSaleable(false);//新录入的商品都是下架状态
        int count = spuMapper.insertSelective(spu);
        if(count!=1){
            throw new LyException(LyExceptionEnum.INSERT_OPERATION_FAIL);
        }
        //保存spuDetail
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
        spuDetail.setSpuId(spu.getId());
        count = spuDetailMapper.insertSelective(spuDetail);
        if(count!=1){
            throw new LyException(LyExceptionEnum.INSERT_OPERATION_FAIL);
        }
        //保存sku列表
        List<SkuDTO> skus = spuDTO.getSkus();
        List<Sku> skuList = new ArrayList<>();
        for (SkuDTO skuDTO : skus) {
            Sku sku = BeanHelper.copyProperties(skuDTO, Sku.class);
            sku.setSpuId(spu.getId());
            sku.setCreateTime(new Date());
            skuList.add(sku);
        }
        count = skuMapper.insertList(skuList);
        if(count!=skuList.size()){
            throw new LyException(LyExceptionEnum.INSERT_OPERATION_FAIL);
        }

    }

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public void updateSaleable(Long id, Boolean saleable) {
        //更新spu上下架状态
        Spu spu = new Spu();
        spu.setId(id);
        spu.setSaleable(saleable);
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if (count!=1) {
            throw new LyException(LyExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        //更新sku是否可用状态
        Sku sku = new Sku();
        sku.setEnable(saleable);
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId",id);
        count = skuMapper.updateByExampleSelective(sku, example);
        //查询满足条件的sku数量
        int size = skuMapper.selectCountByExample(example);
        if(count!=size){
            throw new LyException(LyExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        String routingKey=saleable?MQConstants.RoutingKey.ITEM_UP_KEY:MQConstants.RoutingKey.ITEM_DOWN_KEY;
        //商品上下架，同步操作索引库和静态页服务  高内聚、低耦合   rabbitmq 生产者代码
        amqpTemplate.convertAndSend(MQConstants.Exchange.ITEM_EXCHANGE_NAME,routingKey,id);
    }

    @Override
    public SpuDetailDTO querySpuDetailBySpuId(Long id) {
        SpuDetail spuDetail = spuDetailMapper.selectByPrimaryKey(id);
        if (spuDetail==null) {
            throw new LyException(LyExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spuDetail,SpuDetailDTO.class);
    }

    @Override
    public List<SkuDTO> querySkuBySpuId(Long id) {
        Sku sku = new Sku();
        sku.setSpuId(id);
        List<Sku> skuList = skuMapper.select(sku);
        if (CollectionUtils.isEmpty(skuList)) {
            throw new LyException(LyExceptionEnum.GOODS_NOT_FOUND);
        }

        return BeanHelper.copyWithCollection(skuList,SkuDTO.class);
    }

    @Override
    public void updateGoods(SpuDTO spuDTO) {
        //修改spu
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if(count!=1){
            throw new LyException(LyExceptionEnum.UPDATE_OPERATION_FAIL);
        }
        //修改spuDetail
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
        spuDetail.setSpuId(spu.getId());
        count = spuDetailMapper.updateByPrimaryKeySelective(spuDetail);
        if(count!=1){
            throw new LyException(LyExceptionEnum.UPDATE_OPERATION_FAIL);
        }


        //修改sku  先删除原有sku再新增页面sku数据
        //先删除原有sku
        Sku sku = new Sku();
        sku.setSpuId(spu.getId());

        int size = skuMapper.selectCount(sku);
        count = skuMapper.delete(sku);

        if (size!=count) {
            throw new LyException(LyExceptionEnum.UPDATE_OPERATION_FAIL);
        }


        //再新增页面sku数据
        List<SkuDTO> skuDTOList = spuDTO.getSkus();
        List<Sku> skuList = new ArrayList<>();
        for (SkuDTO skuDTO : skuDTOList) {
            Sku sku1 = BeanHelper.copyProperties(skuDTO, Sku.class);
            sku1.setSpuId(spu.getId());
            skuList.add(sku1);
        }

        count = skuMapper.insertList(skuList);

        if(count!=skuList.size()){
            throw new LyException(LyExceptionEnum.UPDATE_OPERATION_FAIL);
        }

    }

    @Override
    public SpuDTO querySpuBySpuId(Long id) {

        Spu spu = spuMapper.selectByPrimaryKey(id);
        SpuDTO spuDTO = BeanHelper.copyProperties(spu, SpuDTO.class);

        spuDTO.setSpuDetail(querySpuDetailBySpuId(id));

        spuDTO.setSkus(querySkuBySpuId(id));
        return spuDTO;
    }

    @Override
    public List<SkuDTO> querySkuListByIds(List<Long> ids) {

        List<Sku> skuList = skuMapper.selectByIdList(ids);

        if(CollectionUtils.isEmpty(skuList)){
            throw new LyException(LyExceptionEnum.GOODS_NOT_FOUND);
        }

        return BeanHelper.copyWithCollection(skuList,SkuDTO.class);
    }

    @Override
    public void updateStock(Map<Long, Integer> skuMap) {
        for(Long skuId: skuMap.keySet()){
            Integer num =skuMap.get(skuId);
            //更新商品库存
            int count = skuMapper.updateStock(skuId,num);
            if(count!=1){
                throw new LyException(LyExceptionEnum.UPDATE_OPERATION_FAIL);
            }
        }
    }

    @Override
    public void plusStock(Map<Long, Integer> skuMap) {
        for(Long skuId: skuMap.keySet()){
            Integer num =skuMap.get(skuId);
            //更新商品库存
            int count = skuMapper.plusStock(skuId,num);
            if(count!=1){
                throw new LyException(LyExceptionEnum.UPDATE_OPERATION_FAIL);
            }
        }
    }


}
